﻿
using System.Text.RegularExpressions;

namespace ZGDisassembler.UI;

internal class SyntaxHighlighting
{
	internal const int StyleDefault = 0;
	internal const int StyleKeyword = 1;
	internal const int StyleCommand = 2;
	internal const int StyleNumber = 3;

	internal void Highlighting(Scintilla editor, int startPos, int endPos)
	{
		var startLine = editor.LineFromPosition(startPos);

		startPos = editor.Lines[startLine].Position;

		editor.StartStyling(startPos);
		while(startPos < endPos)
		{
			var c = (char)editor.GetCharAt(startPos);
			var line = editor.LineFromPosition(startPos);
			var lineText = editor.Lines[line].Text;
			switch (c)
			{
				case '\r':
				case '\n':
					editor.SetStyling(lineText.Length, StyleDefault);
					startPos += lineText.Length;
					break;
				case '\t':
					var text = editor.Lines[line].Text;
					if (text.StartsWith("\t.ORG") || text.StartsWith("\t.HEX"))
					{
						editor.SetStyling(5, StyleCommand);
						editor.SetStyling(editor.Lines[line].Text.Length - 5, StyleNumber);
					}
					else
					{
						var match = Regex.Match(text, "[^^]\\s");
						if (match.Success)
						{
							var length = match.Index + match.Length;
							editor.SetStyling(length, StyleKeyword);
							editor.SetStyling(lineText.Length - length, StyleDefault);
						}
					}
					startPos += text.Length;
					break;
				default:
					editor.SetStyling(lineText.Length, StyleDefault);
					startPos += lineText.Length;
					break;
			}
		}
	}
}
